<template>
  <el-dialog
    title="新建连接"
    width="350"
    v-model="dialogVisible"
    :show-close="false"
    :modal="true"
    :close-on-click-modal="false"
  >
    <el-form label-width="auto" :model="device">
      <el-form-item label="设备名称:" label-position="right">
        <el-input v-model="device.name"></el-input>
      </el-form-item>
      <el-form-item label="通讯类型:" label-position="right">
        <el-select v-model="device.protocol">
          <el-option
            v-for="protocolType in ProtocolTypeList"
            :key="protocolType"
            :label="protocolType"
            :value="protocolType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="IP地址:" label-position="right">
        <el-input v-model="device.ip"></el-input>
      </el-form-item>
      <el-form-item label="端口号:" label-position="right">
        <el-input v-model.number="device.port"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row class="custom-row">
        <el-form-item class="custom-form-item">
          <el-button type="primary" @click="editCommit">确定</el-button>
        </el-form-item>
        <el-form-item class="custom-form-item">
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-row>
    </template>
  </el-dialog>
</template>

<script setup name="EditConnection" lang="ts">
import {ref, type PropType, onMounted} from "vue";
import {type Device} from "@/types/device";
import {editDevice} from "@/api/deviceApi.ts";
import {ProtocolTypeList} from "@/types/protocol_type.ts";

const dialogVisible = ref(false);
const emit = defineEmits(["editDeviceSuccess", "update:device"]);

let props = defineProps({
  device: {
    type: Object as PropType<Device>,
    required: true,
  },
});

const editCommit = async () => {
  const isSuccess = await editDevice(props.device);
  if (isSuccess) {
    emit(
      "editDeviceSuccess",
      props.device.name,
      props.device.ip,
      props.device.port,
      props.device.protocol,
    );
    closeDialog();
  }
};

const setDevice = (device: Device) => {
  emit('update:device', device); // 触发事件通知父组件
};

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
}

// 如果需要从父组件控制对话框显示
defineExpose({
  openDialog,
  closeDialog,
  setDevice
});
</script>

<style scoped>
.config-container {
  width: 400px;
  padding: 20px;
  text-align: left;
}

.el-form-item {
  margin-bottom: 15px;
}

.custom-row {
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}

/* 如果你不想给第一个和最后一个元素添加边距，可以使用伪类选择器 */
.custom-row .custom-form-item:first-child {
  margin-left: 0;
}

.custom-row .custom-form-item:last-child {
  margin-right: 0;
}
</style>
